// pages/order-detail/order-detail.js
const api = require('../../utils/api.js')
const config = require('../../utils/config.js')
const util = require('../../utils/util.js')

Page({
    data: {
        orderId: '',
        orderInfo: {},
        logs: [],
        statusText: {
            pending: '待处理',
            processing: '处理中',
            completed: '已完成',
            rejected: '已拒绝'
        },
        statusClass: {
            pending: 'status-pending',
            processing: 'status-processing',
            completed: 'status-completed',
            rejected: 'status-rejected'
        }
    },

    onLoad(options) {
        if (options.orderId) {
            this.setData({ orderId: options.orderId })
            this.loadOrderDetail(options.orderId)
        }
    },

    onShow() {
        // 刷新详情
        if (this.data.orderId) {
            this.loadOrderDetail(this.data.orderId)
        }
    },

    // 加载工单详情
    loadOrderDetail(orderId) {
        wx.showLoading({ title: '加载中...' })

        api.getRepairOrderDetail(orderId).then(res => {
            // 格式化时间
            res.created_at = util.formatTime(util.safeDate(res.created_at))
            if (res.updated_at) {
                res.updated_at = util.formatTime(util.safeDate(res.updated_at))
            }

            // 处理图片数组
            if (typeof res.images === 'string') {
                res.images = JSON.parse(res.images)
            }

            this.setData({
                orderInfo: res,
                logs: res.logs || []
            })
        }).catch(err => {
            console.error('加载工单详情失败', err)

            wx.showModal({
                title: '加载失败',
                content: '工单不存在或已删除',
                showCancel: false,
                success: () => {
                    wx.navigateBack()
                }
            })
        }).finally(() => {
            wx.hideLoading()
        })
    },

    // 预览图片
    previewImage(e) {
        const url = e.currentTarget.dataset.url

        wx.previewImage({
            current: url,
            urls: this.data.orderInfo.images
        })
    },

    // 拨打电话
    callPhone() {
        if (this.data.orderInfo.phone) {
            wx.makePhoneCall({
                phoneNumber: this.data.orderInfo.phone
            })
        }
    }
})
